import fp from 'lodash/fp'
import router from './router'
import Router from 'vue-router'
import { constantRouterMap,asyncPluginsMap,asyncRouterMap } from '@/router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import Cookies from 'js-cookie'
import { getToken } from '@/utils/auth'
import $aes from '../src/utils/aes'
NProgress.configure({ showSpinner: false })

function hasPermission(roles, permissionRoles) {
  // console.log(roles, permissionRoles, '=================hasPermission')
  if (!permissionRoles) return true
  return roles.some(role => permissionRoles.indexOf(role) >= 0)
}
const whiteList = store.getters.isToLogin ? ['/login'] : []
router.beforeEach((to, from, oldNext) => {

  console.log(to, from, oldNext,'*****************************');

  NProgress.start()
  // console.log(to.path, store.getters.rolesDefult, 'console.log.path')
  // console.log('store+++++++++++++store',store.state.secondNav);
  //获取当前路由（name）
  const nowPath = to.path.split('/').pop();
  // console.log('store+++++++++++++storeto.path',);

  const needAddBusIdToQuery = !!from.query.store_user_id && !!!to.query.store_user_id
  const newaid = !!from.query.h_aid && !!!to.query.h_aid
  const store_user_id = needAddBusIdToQuery ? from.query.store_user_id : ''
  const h_aid = newaid ? from.query.h_aid : ''

  const outher_query = to.query;
  console.log('一次',store_user_id,from);
  // if(store_user_id) {
  //   console.log('需要bus_id', store_user_id)
  // }else {
  //   console.log('不需要bus_id')
  // }
//城市代理相关，点了代理列表管理之后，代理端的每个页面都会带aagent_id
  const next = (options = {})=> {
    // console.log('2333',options,to)
    if(store_user_id && options.path && h_aid) {
      // console.log('走方式一',store_user_id,outher_query)
      oldNext(fp.merge({
        query: {
          ...outher_query,
          store_user_id,
          h_aid
        }
      }, options))

    } else if(store_user_id && !options.path && h_aid) {
      // console.log('2333:2')
      // console.log('走方式二',store_user_id,outher_query)

      oldNext({
        path: to.path,
        query: {
          ...outher_query,
          store_user_id,
          h_aid
        }
      })
    } else {
      // console.log('走方式三',store_user_id,outher_query)

      // console.log("fdhdfdjid福袋接口发达省份都是",[store_user_id])
      // console.log('2333:3',options.query)
     
      oldNext(options)
    }
  }


  
  
  /**
   * 新版应用路由
   */
  if(store.state.secondNav.navData.length == 0){
    //检测当前路由是否为应用的三级路由
    // console.log('asyncPluginsMapasyncPluginsMap',asyncPluginsMap);
    if (asyncPluginsMap instanceof Array && asyncPluginsMap.length > 0) {
      //存在子路由
      if (
        asyncPluginsMap[0] instanceof Object &&
        !!asyncPluginsMap[0].children
      ) {
        const rootPaths = asyncPluginsMap[0].children,
              secondRoot = [];
              let isApplicationRoot = false;//是否应用二级路由没有

            // console.log('当前路由名称',nowPath);
        rootPaths.map((root) => {
          // 验证是否在应用中
          if(root.name == nowPath){
            //是应用二级路由
            isApplicationRoot = !isApplicationRoot;
          }
          // 主模块，并且模块存在
          if (
            !!root.app_is_model &&
            !!root.app_model &&
            !!root.meta &&
            !!root.meta.display &&
            !!root.meta.display.children &&
            root.meta.display.children instanceof Array &&
            root.meta.display.children.length > 0 
            &&
            root.meta.display.children.indexOf(nowPath) != -1
          ) {
            //当前为三级路由
            isApplicationRoot = false;
            //当前路由为应用级路由三级子路由，获取同等级三级路由
            rootPaths.map(res_1 => {
              //刷新时
               if(Cookies.get("agent_id") && res_1.path!="vipGoodsList"&&res_1.path!="distributorMerchandise"){
                  res_1.hidden=true
                }
                //在代理端时，显示分享免单的路由，并且刷新时不会变成空白
                if( Cookies.get("agent_id") && res_1.path=='freeofCharge'){
                  res_1.hidden=false
                }
                // if( Cookies.get("agent_id") && res_1.path=='freeofChargeSet'){
                //   res_1.hidden=false
                // }
                // if( Cookies.get("agent_id") && res_1.path=='freeofClassify'){
                //   res_1.hidden=false
                // }
                if( Cookies.get("agent_id") && res_1.path=='freeoForder'){
                  res_1.hidden=false
                }

              root.meta.display.children.map(res_2 => {
                if(res_1.name == res_2){
                  secondRoot.push(res_1);
                }
              })
            })
            // console.log('应用级路由',root);
          }
        });

        //如果是三级路由，那么入原本一级路由应用子集
        if(secondRoot.length == 0 && isApplicationRoot){
          // console.log('constantRouterMap',asyncRouterMap);
          asyncRouterMap.map(item_root => {
            if(item_root.path == '/applicationNew'){

              item_root.children.map(item_root_item => {
               
                secondRoot.push({...item_root_item,isApplication:true});
              })
             
            }
          })
        }

        store.commit('SET_NAV_DATA',secondRoot);
      }
    }
  }

  if (to.path !== '/login') {
    document.querySelector('#_weliamtitle').innerHTML = to.meta.title || '管理平台'
  }

  if (to.path === '/dashboard') {
    store.dispatch('setRedirect', to.path)
  }

  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      // console.log(store.getters.inEdition, 'inEdition')
        // console.log('agent_id2322222222222',store.getters.roles);

      if (store.getters.roles.length === 0) {
        const rolesDefult = store.getters.rolesDefult
        const routerPath = store.getters.routerPath
        store.dispatch('ChangeRoles', { 'roles': rolesDefult, 'path': routerPath }).then(() => {
          // console.log({ ...to, replace: true }, store.getters.addRouters, 'store.getters.addRouters')
          router.matcher = new Router({
            routes: [...constantRouterMap]
          }).matcher
          // console.log(store.getters.addRouters, 'matcher1')
          router.addRoutes(store.getters.addRouters)
          // console.log(to, router, 'matcher2')
          next({ ...to, replace: true })
          NProgress.done()
        }).catch(err => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err || '请重新登录!~')
            next({ path: '/', replace: true })
          })
          NProgress.done()
        })
      } else {
        store.dispatch('SetRrouterBefore', from.path)
        if (hasPermission(store.getters.roles, to.meta.roles)) {
          next()
        } else {
          next({ path: '/401', replace: true, query: { noGoBack: true } })
        }
        NProgress.done()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
      NProgress.done()
    } else {
      if (store.getters.isToLogin) {
        next(`/login?redirect=${to.path}`)
      } else {
        location.href = `${location.protocol}//${location.hostname}`
      }
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach((to, from, next) => {
  // console.log(to.meta, 'toggleDropdown')
  store.dispatch('toggleDropdown', (to.meta && to.meta.noDropdown))
  NProgress.done()
})

router.onReady(() => {
})
